<template>
  <div class="accounts-receivable-summary">
    <!-- 查询条件区域 -->
    <div class="search-container">
      <div class="search-row">
        <div class="date-range">
          <span class="label">单据日期:</span>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
          <span class="to-text">至</span>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
        </div>

        <div class="search-item">
          <span class="label">汇总依据</span>
          <el-select
            v-model="summaryBy"
            placeholder="请选择汇总依据"
            class="search-select"
          >
            <el-option label="客户" value="customer" />
            <el-option label="客户类别" value="customertype" /> 
            <el-option label="销售人员" value="salesperson" />
          </el-select>
        </div>

        <!-- 客户 -->
        <div class="search-item" v-if="summaryBy === 'customer'">
          <span class="label">客户</span>
          <el-input
            v-model="selectedCustomerNames"
            placeholder="请选择客户"
            readonly
            class="customer-input"
            @click="openCustomerDialog"
          >
            <template #suffix>
              <el-icon class="select-icon" @click="openCustomerDialog">
                <ArrowDown />
              </el-icon>
            </template>
          </el-input>
        </div>

        <!-- 客户类别 -->
        <div class="search-item" v-if="summaryBy === 'customer' || summaryBy === 'customertype'">
          <span class="label">客户类别</span>
          <el-select
            v-model="customerCategory"
            placeholder="请选择客户类别"
            class="search-select"
          >
            <el-option label="全部类别" value="" />
            <el-option label="广东省内" value="广东省内" />
            <el-option label="测试类别" value="测试类别" />
          </el-select>
        </div>

        <!-- 销售人员 -->
        <div class="search-item" v-if="summaryBy === 'salesperson'">
          <span class="label">销售人员</span>
          <el-select
            v-model="selectedSalesperson" 
            placeholder="请选择销售人员"
            class="search-select"
          >
            <el-option label="全部人员" value="" />
            <el-option label="去" value="去" />
            <el-option label="企鹅" value="企鹅" />
          </el-select>
        </div>

        <div class="search-actions">
          <el-button type="primary" @click="doSearch" class="query-btn"
            >查询</el-button
          >
          <el-button @click="expandConditions" class="expand-btn"
            >展开条件</el-button
          >
        </div>
      </div>

      <!-- 高级查询条件 (默认隐藏) -->
      <div class="advanced-search" v-if="showAdvancedSearch">
        <!-- 可添加更多高级查询条件 -->
      </div>
    </div>

    <!-- 饼状图区域 -->
    <div class="chart-container" v-if="showChart">
      <h2 style="text-align: center">应收账款总览</h2>
      <div class="chart-item" ref="pieChartRef">
        <div class="chart-title">客户应收款占比</div>
        <div class="chart-content"></div>
      </div>
    </div>

    <!-- 报表标题区域 -->
    <div class="report-header">
      <div class="date-range-text">日期: {{ startDate }} 至 {{ endDate }}</div>
      <h2 class="report-title">应收账款汇总表</h2>
      <div class="report-actions">
        <el-button type="primary" class="export-btn">导出</el-button>
        <el-dropdown class="print-btn">
          <el-button type="primary">
            打印
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>打印预览</el-dropdown-item>
              <el-dropdown-item>直接打印</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 表格工具栏 -->
    <!-- <div class="table-tools">
      <el-button
        type="text"
        @click="openCustomerDialog"
        class="select-customer-btn"
      >
        <el-icon><User /></el-icon> 选择客户
      </el-button>
      <span class="selected-count" v-if="selectedCustomers.length > 0">
        已选择 {{ selectedCustomers.length }} 个客户
      </span>
      <el-button type="text" class="column-setting">
        <el-icon><Setting /></el-icon> 列设置
      </el-button>
    </div> -->

    <!-- 数据表格 -->
    <el-table
      :data="filteredTableData"
      border
      :row-class-name="tableRowClassName"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      class="summary-table"
      highlight-current-row
    >
      <!-- 动态列：根据汇总依据显示不同维度列 -->
      <el-table-column
        v-if="summaryBy === 'customer'"
        prop="customerCategory"
        label="客户类别"
        min-width="100"
        sortable
      />
      <el-table-column
        v-if="summaryBy === 'customer'"
        prop="customerCode"
        label="客户编号"
        min-width="100"
        sortable
      />
      <el-table-column
        v-if="summaryBy === 'customer'"
        prop="customerName"
        label="客户名称"
        min-width="150"
        sortable
      />
      <!-- 业务员汇总列 -->
      <el-table-column
        v-if="summaryBy === 'salesperson'"
        prop="salespersonCode"
        label="业务员编号"
        min-width="100"
        sortable
      />
      <el-table-column
        v-if="summaryBy === 'salesperson'"
        prop="salespersonName"
        label="业务员"
        min-width="120"
        sortable
      />

      <!-- 公共财务列 -->
      <el-table-column
        prop="beginningBalance"
        label="期初余额"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>期初余额</span>
            <el-tooltip effect="dark" content="期初余额说明">
              <el-icon class="question-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="currentReceivable"
        label="本期应收"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>本期应收</span>
            <el-tooltip effect="dark" content="本期应收说明">
              <el-icon class="question-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="currentCollection"
        label="本期收款"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>本期收款</span>
            <el-tooltip effect="dark" content="本期收款说明">
              <el-icon class="question-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="endingBalance"
        label="期末余额"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>期末余额</span>
            <el-tooltip effect="dark" content="期末余额说明">
              <el-icon class="question-icon"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 客户选择对话框 -->
    <CustomerMultipleSelectDialog
      ref="customerDialogRef"
      :customer-list="allCustomers"
      :default-selected="selectedCustomers"
      @confirm="handleCustomerSelect"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from "vue";
import {
  ArrowDown,
  // Setting,
  QuestionFilled,
  // User,
} from "@element-plus/icons-vue";
import CustomerMultipleSelectDialog from "@/util/CustomerMultipleSelectDialog.vue";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
} from "echarts/components";
import { PieChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import dayjs from "dayjs";
const selectedSalesperson = ref("");

// 注册组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
]);

// 图表相关
const pieChartRef = ref(null);
const pieInstance = ref(null);
const showChart = ref(true);

// 日期范围
const startDate = ref(dayjs().startOf("month").format("YYYY-MM-DD"));
const endDate = ref(dayjs().format("YYYY-MM-DD"));
// 查询条件
const summaryBy = ref("customer");
const customerCategory = ref("");
const selectedCustomers = ref([]);
const showAdvancedSearch = ref(false);

// 对话框引用
const customerDialogRef = ref(null);

// 计算属性：已选择客户名称字符串
const selectedCustomerNames = computed(() => {
  return selectedCustomers.value.map((c) => c.CustomerName).join(", ");
});

// 计算属性：过滤后的表格数据（只显示选中的客户）
const filteredTableData = computed(() => {
  if (selectedCustomers.value.length === 0) {
    return tableData.value;
  }

  return tableData.value.filter(
    (row) =>
      selectedCustomers.value.some(
        (c) => c.CustomerCode === row.customerCode
      ) || row.customerCategory === "合计"
  );
});

// 表格数据
const tableData = ref([]);

// 表头样式
const headerCellStyle = {
  backgroundColor: "#f5f7fa",
  fontWeight: "bold",
  color: "#303133",
  textAlign: "center",
};

// 计算合计行数据
const calculateSummaryRow = (data) => {
  const baseSummary = {
    beginningBalance: "0",
    currentReceivable: "0",
    currentCollection: "0",
    endingBalance: "0",
  };
  console.log(data)

  // 根据汇总类型添加不同维度的合计标题
  if (summaryBy.value === "customer") {
    return {
      ...baseSummary,
      customerCategory: "合计",
      customerCode: "",
      customerName: "",
    };
  } else {
    return {
      ...baseSummary,
      salespersonCode: "",
      salespersonName: "合计",
    };
  }
};
// 新增：监听汇总依据变化，触发查询
watch(
  summaryBy,
  () => {
    doSearch(); // 切换汇总类型时重新查询数据
    selectedCustomers.value = []; // 清空客户选择（仅客户维度有效）
  },
  { immediate: false }
);

// 辅助函数：货币金额相加
const addCurrency = (a, b) => {
  const numA = parseFloat(a.toString().replace(/,/g, "")) || 0;
  const numB = parseFloat(b.toString().replace(/,/g, "")) || 0;
  return (numA + numB).toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

console.log(addCurrency)

// 更新表格数据（自动计算合计行）
const updateTableData = (newData) => {
  const dataWithoutSummary = newData.filter(
    (item) => item.customerCategory !== "合计"
  );
  const summaryRow = calculateSummaryRow(dataWithoutSummary);
  tableData.value = [...dataWithoutSummary, summaryRow];
  updatePieChart();
};

// 单元格样式
const cellStyle = ({ row }) => {
  if (row.customerCategory === "合计") {
    return {
      backgroundColor: "#fff8e6",
      fontWeight: "bold",
    };
  }
  return { textAlign: "center" };
};

// 行类名
const tableRowClassName = ({ row }) => {
  return row.customerCategory === "合计" ? "summary-row" : "";
};

// 打开客户选择对话框
const openCustomerDialog = () => {
  customerDialogRef.value.open();
};

// 处理客户选择结果
const handleCustomerSelect = (customers) => {
  selectedCustomers.value = customers;
  doSearch();
};

// 模拟数据 - 客户数据和应收款数据
const mockCustomersData = ref([
  {
    CustomerCode: "G00009",
    CustomerName: "测试111",
    CustomerType: "",
    ContactPerson: "联系人1",
    ContactPhone: "13800138000",
    financialData: {
      beginningBalance: "-1,992.02",
      currentReceivable: "500.00",
      currentCollection: "200.00",
      endingBalance: "-1,692.02",
    },
  },
  {
    CustomerCode: "G00010",
    CustomerName: "深圳蓝天食品公司",
    CustomerType: "广东省内",
    ContactPerson: "联系人2",
    ContactPhone: "13900139000",
    financialData: {
      beginningBalance: "-2,064.99",
      currentReceivable: "1,000.00",
      currentCollection: "500.00",
      endingBalance: "-1,564.99",
    },
  },
  {
    CustomerCode: "G00011",
    CustomerName: "广州白云贸易公司",
    CustomerType: "广东省内",
    ContactPerson: "联系人3",
    ContactPhone: "13700137000",
    financialData: {
      beginningBalance: "-3,000.00",
      currentReceivable: "2,000.00",
      currentCollection: "1,500.00",
      endingBalance: "-2,500.00",
    },
  },
]);

// 模拟业务员数据
const mockSalespersonData = ref([
  {
    salespersonCode: "D0003",
    salespersonName: "采购-小陈",
    financialData: {
      beginningBalance: "1,771.86",
      currentReceivable: "0.00",
      currentCollection: "0.00",
      endingBalance: "1,771.86",
    },
  },
  {
    salespersonCode: "D0004",
    salespersonName: "采购-小王",
    financialData: {
      beginningBalance: "-4,716.31",
      currentReceivable: "0.00",
      currentCollection: "0.00",
      endingBalance: "-4,716.31",
    },
  },
]);

// 根据汇总依据获取数据源
const getTableDataBySummaryType = () => {
  if (summaryBy.value === "customer") {
    // 客户维度数据
    return mockCustomersData.value.map((customer) => ({
      customerCategory: customer.CustomerType,
      customerCode: customer.CustomerCode,
      customerName: customer.CustomerName,
      ...customer.financialData,
    }));
  } else {
    // 业务员维度数据
    return mockSalespersonData.value.map((salesperson) => ({
      salespersonCode: salesperson.salespersonCode,
      salespersonName: salesperson.salespersonName,
      ...salesperson.financialData,
    }));
  }
};

// 查询数据
const doSearch = () => {
  console.log("查询条件:", {
    summaryBy: summaryBy.value,
    startDate: startDate.value,
    endDate: endDate.value,
    selectedCustomers: selectedCustomers.value,
    customerCategory: customerCategory.value,
    selectedSalesperson: selectedSalesperson.value, 
  });

  // 根据汇总类型获取数据
  let tableDataFromSource = getTableDataBySummaryType();
  if (summaryBy.value === "customer") {
    // 客户维度：过滤客户和客户类别
    tableDataFromSource = tableDataFromSource.filter(row => {
      // 客户过滤（选中客户时生效）
      const customerFilter = selectedCustomers.value.length === 0 
        ? true 
        : selectedCustomers.value.some(c => c.CustomerCode === row.customerCode);
      // 客户类别过滤
      const categoryFilter = customerCategory.value === "" 
        ? true 
        : row.customerCategory === customerCategory.value;
      return customerFilter && categoryFilter;
    });
  } else if (summaryBy.value === "customertype") {
    // 客户类别维度：过滤客户类别
    tableDataFromSource = tableDataFromSource.filter(row => {
      return customerCategory.value === "" ? true : row.customerCategory === customerCategory.value;
    });
  } else if (summaryBy.value === "salesperson") {
    // 销售人员维度：过滤销售人员
    tableDataFromSource = tableDataFromSource.filter(row => {
      return selectedSalesperson.value === "" 
        ? true 
        : row.salespersonName === selectedSalesperson.value;
    });
  }

  updateTableData(tableDataFromSource);
};


// 计算属性：获取所有客户列表（不含财务数据）
const allCustomers = computed(() => {
  return mockCustomersData.value.map((customer) => {
    return {
      CustomerCode: customer.CustomerCode,
      CustomerName: customer.CustomerName,
      CustomerType: customer.CustomerType,
      ContactPerson: customer.ContactPerson,
      ContactPhone: customer.ContactPhone,
    };
  });
});

// 获取饼图数据（根据选中的客户）
const getPieDataFromTable = () => {
  const dataToShow = tableData.value.filter(item => 
    item.customerCategory !== "合计" && item.salespersonCode !== "合计"
  );

  // 根据汇总类型生成不同饼图数据
  if (summaryBy.value === "customer") {
    return dataToShow.map((item) => ({
      value: Math.abs(parseFloat(item.endingBalance.replace(/,/g, "")) || 0),
      name: item.customerName || "未命名客户",
      customerCode: item.customerCode,
    }));
  } else {
    return dataToShow.map((item) => ({
      value: Math.abs(parseFloat(item.endingBalance.replace(/,/g, "")) || 0),
      name: item.salespersonName || "未命名业务员",
      salespersonCode: item.salespersonCode,
    }));
  }
};

// 初始化饼图
const initPieChart = () => {
  nextTick(() => {
    if (pieChartRef.value && !pieInstance.value) {
      const chartDom = pieChartRef.value.querySelector(".chart-content");
      pieInstance.value = echarts.init(chartDom);
      updatePieChart();

      // 响应式调整大小
      window.addEventListener("resize", () => {
        pieInstance.value?.resize();
      });
    }
  });
};

// 更新饼图
const updatePieChart = () => {
  if (!pieInstance.value) return;

  const pieData = getPieDataFromTable();

  // 如果没有数据，显示空状态
  if (pieData.length === 0) {
    pieInstance.value.setOption({
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: "normal",
          color: "#999",
        },
      },
      series: [],
    });
    return;
  }

  const option = {
    title: {
      text: "客户应收款占比",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const selectedCustomer = selectedCustomers.value.find(
          (c) => c.CustomerCode === params.data.customerCode
        );
        const contactInfo = selectedCustomer
          ? `<br/>联系人: ${selectedCustomer.ContactPerson || "无"}
             <br/>电话: ${selectedCustomer.ContactPhone || "无"}`
          : "";

        return `
          <strong>${params.name}</strong><br/>
          金额: ${params.value.toLocaleString("zh-CN", {
            style: "currency",
            currency: "CNY",
          })}<br/>
          占比: ${params.percent}%
          ${contactInfo}
        `;
      },
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
      data: pieData.map((item) => item.name),
    },
    series: [
      {
        name: "应收款占比",
        type: "pie",
        radius: ["40%", "70%"],
        data: pieData,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}: {c}元",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: true,
        },
      },
    ],
  };

  pieInstance.value.setOption(option);
};

// 监听选中的客户变化，更新饼图
watch(
  selectedCustomers,
  () => {
    updatePieChart();
  },
  { deep: true }
);

// 展开/收起高级条件
const expandConditions = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value;
};

onMounted(() => {
  if (summaryBy.value === "customer") {
    selectedCustomers.value = [...allCustomers.value]; // 仅客户维度默认选中所有客户
  }
  doSearch();
  initPieChart();
});
</script>

<style scoped>
/* 基础样式 */
.accounts-receivable-summary {
  padding: 15px;
  background-color: #fff;
  min-height: 100vh;
}

/* 查询区域样式 */
.search-container {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.search-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.label {
  color: #606266;
  margin-right: 10px;
  white-space: nowrap;
}

.date-range {
  display: flex;
  align-items: center;
  margin-right: 25px;
}

.date-picker {
  width: 140px;
  margin-right: 10px;
}

.to-text {
  margin-right: 10px;
  color: #606266;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 25px;
  margin-bottom: 10px;
}

.search-select {
  width: 160px;
}

.search-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.query-btn {
  background-color: #409eff;
}

.expand-btn {
  color: #606266;
  background-color: #fff;
  border: 1px solid #dcdfe6;
}

/* 客户输入框样式 */
.customer-input {
  width: 300px;
  cursor: pointer;
}

.select-icon {
  cursor: pointer;
  color: #c0c4cc;
}

.select-icon:hover {
  color: #409eff;
}

/* 报表标题区域 */
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.date-range-text {
  color: #606266;
  font-size: 14px;
}

.report-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: bold;
}

.report-actions {
  display: flex;
  gap: 10px;
}

.export-btn {
  background-color: #1890ff;
}

.print-btn {
  background-color: #409eff;
}

/* 表格样式 */
:deep(.el-table) {
  width: 100%;
  margin-bottom: 15px;
}

.header-with-tooltip {
  display: flex;
  align-items: center;
  justify-content: center;
}

.question-icon {
  margin-left: 5px;
  color: #909399;
  cursor: help;
}

/* 表格工具栏 */
.table-tools {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.select-customer-btn {
  color: #606266;
}

.selected-count {
  margin-left: 15px;
  color: #606266;
  font-size: 14px;
}

.column-setting {
  margin-left: auto;
  color: #606266;
}

/* 高级搜索区域 */
.advanced-search {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e4e7ed;
}

/* 金额列样式 */
:deep(.el-table .cell) {
  white-space: nowrap;
}

/* 合计行样式 */
:deep(.el-table .el-table__row.summary-row) {
  background-color: #f8f8f8 !important;
  font-weight: bold;
}

:deep(.el-table .el-table__row.summary-row:hover > td) {
  background-color: #fff4bf !important;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}

/* 图表容器样式 */
.chart-container {
  margin-bottom: 30px;
}

.chart-item {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #eaecef;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  margin-bottom: 20px;
}

.chart-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.chart-title {
  padding: 12px 16px;
  font-size: 15px;
  font-weight: 600;
  color: #4a5568;
  background: #f8f9fa;
  border-bottom: 1px solid #eaecef;
}
:deep(.el-table .salesperson-column) {
  text-align: left;
}
.chart-content {
  width: 100%;
  height: 400px;
  padding: 16px;
  box-sizing: border-box;
}
</style>